package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @Author Justin Parker
 * @Date 2024/7/30 0030 17:40
 * @Version 1.0
 */
/*
 * 使用预编译SQL实现注册功能
 * 1.用户输入:用户名、密码、昵称、年龄;
 * 2.返回结果
 *  2.1 用户名被占用，注册失败[select id from userinfo where username=?];
 *  2.2 注册成功;[insert into userinfo(username,password,nickname,age)values(?,?,?,?)];
 */
public class JDBCReg {
    public static void main(String[] args) {
        try(Connection connection = DBUtil.getConnection()) {

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String username = scanner.nextLine();
            System.out.println("请输入密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称：");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄：");
            Integer age = scanner.nextInt();

            String sql1 = "select id from userinfo where username=?";
            String sql2 = "insert into userinfo(username,password,nickname,age)values(?,?,?,?)";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ps1.setString(1,username);

            ResultSet resultSet1 = ps1.executeQuery();
            if (resultSet1.next()){
                System.out.println("用户名被占用，注册失败");
            }else {
                ps2.setString(1,username);
                ps2.setString(2,password);
                ps2.setString(3,nickname);
                ps2.setInt(4,age);
                int i = ps2.executeUpdate();
                if (i>0){
                    System.out.println("注册成功");
                }else {
                    System.out.println("注册失败");
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
